﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using Aspose.Words;
using CellsPdfDocument = Aspose.Cells.PdfSaveOptions;

namespace Utils
{
    public class AsposeUtils
    {
        public static bool WordToPDF(string sourcePath, string pdfPath="")
        {
            try
            {
                string extend = Path.GetExtension(sourcePath);
                if (string.IsNullOrEmpty(pdfPath))
                    pdfPath = sourcePath.Replace(extend, ".pdf");//pdf存放位置
                if (!File.Exists(@pdfPath))//存在PDF，不需要继续转换
                {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    Document doc = new Document(sourcePath);
                    // 保存转换的pdf文件
                    doc.Save(pdfPath, Aspose.Words.SaveFormat.Pdf);
                }
            }
            catch (Exception e)
            {
                //Logger.Default.Error("pdf转换失败:" + e.Message);    
                LogicLog.WriteLogicLog($"word2pdf转换失败:{e.Message}","");
                return false;
            }
            return true;
        }

        public static bool ExcelToPdf(string sourcePath, string pdfPath = "")
        {
            bool result = false;
            try
            {
                string extend = Path.GetExtension(sourcePath);
                //string PDFPath = sourcePath.Replace(extend, ".pdf");//pdf存放位置
                if (string.IsNullOrEmpty(pdfPath))
                    pdfPath = sourcePath.Replace(extend, ".pdf");//pdf存放位置
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Workbook xls = new Workbook(sourcePath);
                CellsPdfDocument xlsSaveOption = new CellsPdfDocument();
                xlsSaveOption.SecurityOptions = new Aspose.Cells.Rendering.PdfSecurity.PdfSecurityOptions();
                xlsSaveOption.SecurityOptions.ExtractContentPermission = false;
                xlsSaveOption.SecurityOptions.PrintPermission = false;
                xlsSaveOption.AllColumnsInOnePagePerSheet = true;
                xls.Save(pdfPath, xlsSaveOption);
                result = true;
            }
            catch (Exception e)
            {
                LogicLog.WriteLogicLog($"excel2pdf转换失败:{e.Message}", "");
            }
            return result;
        }
    }
}
